<template>
  <div class="labor-publish">
    <div class="page-header">
      <h2>劳务发布</h2>
      <p>发布您的劳务需求，让学生为您提供服务</p>
    </div>

    <el-card class="publish-card">
      <div slot="header" class="card-header">
        <span>发布新劳务</span>
        <el-button type="primary" @click="showPublishDialog = true">
          <i class="el-icon-plus"></i>
          发布劳务
        </el-button>
      </div>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="工作标题">
            <el-input
              v-model="searchForm.jobTitle"
              placeholder="请输入工作标题"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          
          <el-form-item label="劳务类型">
            <el-select
              v-model="searchForm.typeId"
              placeholder="请选择类型"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="item in laborTypes"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="工作类型">
            <el-select
              v-model="searchForm.workType"
              placeholder="请选择工作类型"
              clearable
              style="width: 130px"
            >
              <el-option label="兼职" value="part-time" />
              <el-option label="全职" value="full-time" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 130px"
            >
              <el-option label="待审核" value="pending" />
              <el-option label="招聘中" value="recruiting" />
              <el-option label="已完成" value="completed" />
              <el-option label="已关闭" value="closed" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 劳务列表 -->
      <el-table
        :data="laborList"
        v-loading="loading"
        style="width: 100%"
        empty-text="暂无劳务信息"
      >
        <el-table-column prop="jobTitle" label="工作标题" min-width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="labor-title">{{ scope.row.jobTitle }}</span>
            <el-tag v-if="scope.row.urgent === 1" type="danger" size="mini" style="margin-left: 5px">紧急</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="typeName" label="劳务类型" width="110" show-overflow-tooltip />
        
        <el-table-column prop="location" label="工作地点" width="100" show-overflow-tooltip />
        
        <el-table-column prop="workType" label="工作类型" width="90">
          <template slot-scope="scope">
            <el-tag :type="scope.row.workType === 'full-time' ? 'success' : 'info'" size="small">
              {{ scope.row.workType === 'full-time' ? '全职' : '兼职' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="salary" label="薪资" width="100">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.salary }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="requiredCount" label="需要人数" width="90" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.requiredCount }}人</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="applyCount" label="申请人数" width="90" align="center">
          <template slot-scope="scope">
            <span style="color: #409EFF;">{{ scope.row.applyCount || 0 }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="90">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="发布时间" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="210" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="viewLabor(scope.row)">查看</el-button>
            <el-button size="mini" type="primary" @click="editLabor(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteLabor(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>

    <!-- 发布/编辑劳务对话框 -->
    <el-dialog
      :title="isEdit ? '编辑劳务' : '发布劳务'"
      :visible.sync="showPublishDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form
        :model="laborForm"
        :rules="laborRules"
        ref="laborForm"
        label-width="100px"
      >
        <!-- 基本信息 -->
        <div class="form-section-title">基本信息</div>
        
        <el-form-item label="劳务类型" prop="typeId">
          <el-select
            v-model="laborForm.typeId"
            placeholder="请选择劳务类型"
            style="width: 100%"
            @change="onTypeChange"
          >
            <el-option
              v-for="item in laborTypes"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="工作标题" prop="jobTitle">
          <el-input
            v-model="laborForm.jobTitle"
            placeholder="请输入工作标题，如：家教辅导数学"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="工作地点" prop="location">
          <el-select
            v-model="laborForm.location"
            placeholder="请选择工作地点"
            style="width: 100%"
          >
            <el-option
              v-for="item in locationOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        
        <!-- 工作设置 -->
        <div class="form-section-title">工作设置</div>
        
        <el-form-item label="工作类型" prop="workType">
          <el-radio-group v-model="laborForm.workType">
            <el-radio label="part-time">兼职</el-radio>
            <el-radio label="full-time">全职</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="薪资待遇" prop="salary">
          <el-input-number
            v-model="laborForm.salary"
            :min="0"
            :precision="2"
            placeholder="请输入一口价"
            style="width: 200px"
          />
          <span style="margin-left: 10px; color: #999;">元/次</span>
        </el-form-item>
        
        <el-form-item label="需要人数" prop="requiredCount">
          <el-input-number
            v-model="laborForm.requiredCount"
            :min="1"
            :max="99"
            placeholder="需要人数"
            style="width: 200px"
          />
          <span style="margin-left: 10px; color: #999;">人</span>
        </el-form-item>
        
        <el-form-item label="紧急招聘">
          <el-switch
            v-model="laborForm.urgent"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
          />
          <span style="margin-left: 10px; color: #999; font-size: 12px;">紧急招聘可增加曝光度</span>
        </el-form-item>
        
        <!-- 详细描述 -->
        <div class="form-section-title">详细描述</div>
        
        <el-form-item label="工作描述" prop="description">
          <el-input
            type="textarea"
            v-model="laborForm.description"
            placeholder="请详细描述工作内容、职责等"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="任职要求" prop="requirements">
          <el-input
            type="textarea"
            v-model="laborForm.requirements"
            placeholder="请详细说明对应聘者的要求，如：技能、经验、性格等"
            :rows="3"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="联系方式" class="contact-form-item">
          <div class="contact-row">
            <span class="contact-label">QQ</span>
            <el-input
              v-model="laborForm.qq"
              placeholder="请输入QQ号"
              maxlength="20"
              class="contact-input"
            />
          </div>
          <div class="contact-row">
            <span class="contact-label">手机</span>
            <el-input
              v-model="laborForm.phone"
              placeholder="请输入手机号"
              maxlength="11"
              class="contact-input"
            />
          </div>
          <div class="contact-row">
            <span class="contact-label">微信</span>
            <el-input
              v-model="laborForm.wechat"
              placeholder="请输入微信号"
              maxlength="20"
              class="contact-input"
            />
          </div>
          <div class="contact-tip">至少填写一项联系方式</div>
        </el-form-item>
        
        <!-- 图片上传 -->
        <div class="form-section-title">相关图片</div>
        
        <el-form-item label="工作图片">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            list-type="picture-card"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :limit="3"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div style="color: #999; font-size: 12px;">可上传工作环境、公司介绍等相关图片，最多3张</div>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPublishDialog = false">取消</el-button>
        <el-button type="primary" @click="submitLabor" :loading="submitting">
          {{ isEdit ? '更新' : '发布' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "LaborPublish",
  data() {
    return {
      loading: false,
      submitting: false,
      showPublishDialog: false,
      isEdit: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      laborList: [],
      laborTypes: [], // 劳务类型列表
      locationOptions: ['校内', '校外', '线上', '市中心', '商业区'], // 工作地点选项
      fileList: [], // 图片列表
      searchForm: {
        jobTitle: '',
        typeId: null,
        workType: '',
        status: ''
      },
      laborForm: {
        id: null,
        typeId: null,
        typeName: "",
        jobTitle: "",
        location: "",
        workType: "part-time",
        salary: 0,
        requiredCount: 1,
        urgent: 0,
        description: "",
        requirements: "",
        qq: "",
        phone: "",
        wechat: "",
        images: ""
      },
      laborRules: {
        typeId: [
          { required: true, message: "请选择劳务类型", trigger: "change" }
        ],
        jobTitle: [
          { required: true, message: "请输入工作标题", trigger: "blur" },
          { min: 2, max: 50, message: "标题长度在 2 到 50 个字符", trigger: "blur" }
        ],
        location: [
          { required: true, message: "请输入工作地点", trigger: "blur" }
        ],
        workType: [
          { required: true, message: "请选择工作类型", trigger: "change" }
        ],
        salary: [
          { required: true, message: "请输入薪资待遇", trigger: "blur" },
          { type: "number", min: 0, message: "薪资不能小于0", trigger: "blur" }
        ],
        requiredCount: [
          { required: true, message: "请输入需要人数", trigger: "blur" },
          { type: "number", min: 1, message: "至少需要1人", trigger: "blur" }
        ],
        description: [
          { required: true, message: "请输入工作描述", trigger: "blur" },
          { min: 10, max: 500, message: "描述长度在 10 到 500 个字符", trigger: "blur" }
        ],
        requirements: [
          { required: true, message: "请输入任职要求", trigger: "blur" },
          { min: 5, max: 300, message: "要求长度在 5 到 300 个字符", trigger: "blur" }
        ]
      }
    }
  },
  computed: {
    uploadUrl() {
      // 使用商户专用的上传接口（带权限验证）
      return this.$http.defaults.baseURL + '/merchant/upload'
    },
    uploadHeaders() {
      // 获取token并设置到上传请求的headers中
      const token = localStorage.getItem('token')
      return {
        'Authorization': `Bearer ${token}`
      }
    }
  },
  mounted() {
    this.loadLaborList()
    this.loadLaborTypes()
  },
  methods: {
    async loadLaborList() {
      this.loading = true
      try {
        // 构建请求参数，包含分页和搜索条件
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          ...this.searchForm // 合并搜索表单数据
        }
        
        // 过滤空值
        Object.keys(params).forEach(key => {
          if (params[key] === '' || params[key] === null) {
            delete params[key]
          }
        })
        
        const response = await this.$http.get("/merchant/labors", { params })
        if (response.data.code === 200) {
          this.laborList = response.data.data.list || []
          this.total = response.data.data.total || 0
        }
      } catch (error) {
        console.error("获取劳务列表失败:", error)
        this.$message.error("获取劳务列表失败")
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      // 重置到第一页，然后加载数据
      this.currentPage = 1
      this.loadLaborList()
    },

    handleReset() {
      // 重置搜索表单
      this.searchForm = {
        jobTitle: '',
        typeId: null,
        workType: '',
        status: ''
      }
      // 重置到第一页，然后加载数据
      this.currentPage = 1
      this.loadLaborList()
    },

    async loadLaborTypes() {
      try {
        const response = await this.$http.get("/admin/labor-types", {
          params: {
            page: 1,
            size: 100,
            status: 1  // 只获取启用状态的类型
          }
        })
        if (response.data.code === 200) {
          this.laborTypes = response.data.data.records || []
        }
      } catch (error) {
        console.error("获取劳务类型失败:", error)
        this.$message.error("获取劳务类型失败")
      }
    },

    onTypeChange(typeId) {
      const selectedType = this.laborTypes.find(item => item.id === typeId)
      if (selectedType) {
        this.laborForm.typeName = selectedType.typeName
      }
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadLaborList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.loadLaborList()
    },

    viewLabor() {
      this.$message.info("查看功能开发中")
    },

    editLabor(row) {
      this.isEdit = true
      this.laborForm = { ...row }
      this.showPublishDialog = true
    },

    async deleteLabor(row) {
      try {
        await this.$confirm("确定要删除这条劳务信息吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })

        const response = await this.$http.delete(`/merchant/labors/${row.id}`)
        if (response.data.code === 200) {
          this.$message.success("删除成功")
          this.loadLaborList()
        } else {
          this.$message.error(response.data.message || "删除失败")
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除劳务失败:", error)
          this.$message.error("删除失败")
        }
      }
    },

    async submitLabor() {
      try {
        await this.$refs.laborForm.validate()
        
        // 验证至少填写一项联系方式
        if (!this.laborForm.qq && !this.laborForm.phone && !this.laborForm.wechat) {
          this.$message.warning("请至少填写一项联系方式")
          return
        }
        
        this.submitting = true

        const url = this.isEdit ? `/merchant/labors/${this.laborForm.id}` : "/merchant/labors"
        const method = this.isEdit ? "put" : "post"
        
        const response = await this.$http[method](url, this.laborForm)
        if (response.data.code === 200) {
          this.$message.success(this.isEdit ? "更新成功" : "发布成功")
          this.showPublishDialog = false
          this.loadLaborList()
        } else {
          this.$message.error(response.data.message || (this.isEdit ? "更新失败" : "发布失败"))
        }
      } catch (error) {
        console.error("提交劳务失败:", error)
        this.$message.error(this.isEdit ? "更新失败" : "发布失败")
      } finally {
        this.submitting = false
      }
    },

    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.fileList = fileList
        const images = fileList.map(item => {
          return item.response ? item.response.data : item.url
        })
        this.laborForm.images = JSON.stringify(images)
      } else {
        this.$message.error(response.message || "上传失败")
      }
    },

    handleRemove(file, fileList) {
      this.fileList = fileList
      const images = fileList.map(item => {
        return item.response ? item.response.data : item.url
      })
      this.laborForm.images = JSON.stringify(images)
    },

    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件！')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB！')
        return false
      }
      return true
    },

    handleExceed() {
      this.$message.warning('最多只能上传3张图片')
    },

    resetForm() {
      this.isEdit = false
      this.fileList = []
      this.laborForm = {
        id: null,
        typeId: null,
        typeName: "",
        jobTitle: "",
        location: "",
        workType: "part-time",
        salary: 0,
        requiredCount: 1,
        urgent: 0,
        description: "",
        requirements: "",
        qq: "",
        phone: "",
        wechat: "",
        images: ""
      }
      this.$nextTick(() => {
        this.$refs.laborForm && this.$refs.laborForm.clearValidate()
      })
    },

    getStatusType(status) {
      const typeMap = {
        "pending": "warning",     // 待审核
        "recruiting": "success",  // 招聘中
        "completed": "info",      // 已完成
        "closed": "danger"        // 已关闭
      }
      return typeMap[status] || "info"
    },

    getStatusText(status) {
      const textMap = {
        "pending": "待审核",
        "recruiting": "招聘中",
        "completed": "已完成",
        "closed": "已关闭"
      }
      return textMap[status] || "未知"
    },

    formatDate(dateString) {
      if (!dateString) return ""
      const date = new Date(dateString)
      return date.toLocaleString("zh-CN")
    }
  }
}
</script>

<style scoped>
.labor-publish {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.publish-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.search-bar {
  padding: 20px 0;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  padding: 0 20px;
}

.search-form .el-form-item {
  margin-bottom: 10px;
}

.labor-title {
  font-weight: 500;
  color: #333;
}

.price {
  color: #f56c6c;
  font-weight: 600;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  margin-top: 0;
}

.el-card {
  border-radius: 8px;
}

.el-dialog {
  border-radius: 8px;
}

.el-form-item {
  margin-bottom: 20px;
}

.form-section-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin: 20px 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.form-section-title:first-child {
  margin-top: 0;
}

.contact-form-item .contact-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.contact-form-item .contact-row:last-of-type {
  margin-bottom: 0;
}

.contact-form-item .contact-label {
  width: 50px;
  font-size: 14px;
  color: #606266;
  flex-shrink: 0;
}

.contact-form-item .contact-input {
  flex: 1;
}

.contact-form-item .contact-tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
  line-height: 1.5;
}
</style>